<template>
    <el-main>
        <div class="left">
            <el-form :model="userInfo" ref="userInfoForm" label-width="80px" :inline="true" :rules="rules">
                <el-form-item label="姓名" prop="nickName">
                    <el-input v-model="userInfo.nickName" disabled></el-input>
                </el-form-item>
                <el-form-item label="学号" prop="username">
                    <el-input v-model="userInfo.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="身份证" prop="idCard">
                    <el-input v-model="userInfo.idCard" disabled></el-input>
                </el-form-item>
                <el-form-item label="出生日期" prop="dateOfBirth">
                    <el-date-picker v-model="userInfo.dateOfBirth" type="date" placeholder="选择日期" format="yyyy 年 MM 月 dd 日"
                        value-format="yyyy-MM-dd" style="width:190px">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="手机号" prop="telephone">
                    <el-input v-model="userInfo.telephone"></el-input>
                </el-form-item>
                <el-form-item label="班级" prop="classId">
                    <el-input v-model="classRoom" disabled></el-input>
                </el-form-item>
                <el-form-item label="学制" prop="academicYear">
                    <el-input v-model="userInfo.academicYear" disabled></el-input>
                </el-form-item>
                <el-form-item label="学历" prop="culturalLevelId">
                    <el-input v-model="cule" disabled></el-input>
                </el-form-item>
                <el-form-item label="入学时间" prop="admissionYear">
                    <el-date-picker v-model="userInfo.admissionYear" type="date" placeholder="选择日期"
                        format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd" disabled style="width:190px">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="民族" prop="nationalityId">
                    <el-select v-model="userInfo.nationalityId" placeholder="民族" style="width:190px">
                        <el-option v-for="item in nationalityList" :key="item.id" :label="item.value"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="政治面貌" prop="politicalStatusId">
                    <el-select v-model="userInfo.politicalStatusId" placeholder="政治面貌" style="width:190px">
                        <el-option v-for="item in politicalStatusList" :key="item.id" :label="item.value"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                    <el-select v-model="userInfo.sex" placeholder="性别" disabled style="width:190px">
                        <el-option v-for="item in sexProp" :key="item.id" :label="item.value"
                            :value="item.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="userInfo.email"></el-input>
                </el-form-item>
                <el-form-item label="生源地：">
                    {{ userInfo.birthplace }}
                </el-form-item>
                <el-form-item label="生源地" prop="birthplace">
                    <el-select v-model="myBirthplace.province" placeholder="省" @change="findMunicipal()">
                        <el-option v-for="item in provinceList" :key="item.id" :label="item.value"
                            :value="item.code"></el-option>
                    </el-select>
                    <el-select v-model="myBirthplace.municipal" placeholder="市" @change="findCounty()">
                        <el-option v-for="item in municipalList" :key="item.id" :label="item.value"
                            :value="item.code"></el-option>
                    </el-select>
                    <el-select v-model="myBirthplace.county" placeholder="区" @change="makeBirthPlace()">
                        <el-option v-for="item in countyList" :key="item.id" :label="item.value"
                            :value="item.code"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="家庭住址" prop="homeAddress">
                    <el-input v-model="userInfo.homeAddress" type="textarea" :rows="4" style="width:450px"></el-input>
                </el-form-item>
            </el-form>
            <div class="button"><el-button type="success" @click="pushUserInfo()">提交信息</el-button></div>
        </div>
        <div class="right">
            <el-form :model="userInfo" label-width="80px" :inline="true">
                <el-form-item label="照片">
                    <el-upload :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"
                        class="avatar-uploader" :data="uploadHeader"
                        action="http://localhost:8888/api/oss/file/upload?module=photoId">
                        <img v-if="userInfo.photoId" :src="userInfo.photoId">
                        <i v-else class="el-icon-plus avatar-uploader-icon" />
                    </el-upload>
                </el-form-item>
            </el-form>
        </div>
    </el-main>
</template>

<script>
import userApi from '@/api/user'
import commonApi from '@/api/common'
import areaApi from '@/api/area'
import classApi from '@/api/class'
import { getToken } from '@/utils/auth'

export default {
    name: 'register',
    data() {
        return {
            userInfo: {},
            codeCulturalLevel: [],
            nationalityList: [],
            politicalStatusList: [],
            sexProp: [
                { id: 1, value: '男', },
                { id: 2, value: '女', },
            ],
            classList: [],
            culturalLevelList: [],
            provinceList: [],//省
            municipalList: [],//市
            countyList: [],//区
            myBirthplace: {
                province: '',
                municipal: '',
                county: '',
            },
            rules:{
                dateOfBirth: [{ required: true, trigger: "change", message: "请输入出生日期" }],
                nationalityId: [{ required: true, trigger: "change", message: "请选择民族" }],
                politicalStatusId:[{ required: true, trigger: "change", message: "请选择政治面貌" }],
                birthplace:[{ required: true, trigger: "change", message: "请选择生源地" }],
                homeAddress:[{ required: true, trigger: "blur", message: "请输入家庭住址" }],
            },

            classRoom: '',
            cule: '',
            uploadHeader: { "token": getToken() },
        }
    },
    methods: {
        async init() {
            let userId = this.$store.getters.userId
            let [userRes, culturalRes, naRes, poRes, provinceRes, classRes, cuRes] =
                await Promise.all([userApi.getUserList({ id: userId }),
                commonApi.getCodeCulturalLevel(), commonApi.getNationality(),
                commonApi.getPoliticalStatus(), areaApi.getProvinceList(),
                classApi.getClassList(), commonApi.getCodeCulturalLevel()])
            this.userInfo = userRes.data.records[0]
            this.codeCulturalLevel = culturalRes.data
            this.nationalityList = naRes.data
            this.politicalStatusList = poRes.data
            this.provinceList = provinceRes.data
            this.classList = classRes.data.records
            console.log(cuRes)
            this.culturalLevelList = cuRes.data

            const classRoom = this.classList.find(classRoom => classRoom.id === this.userInfo.classId)
            this.classRoom = classRoom.className

            const cule = this.culturalLevelList.find(cule => cule.id === this.userInfo.culturalLevelId)
            this.cule = cule.value

        },
        async findMunicipal() {
            let res = await areaApi.getMunicipalList({ code: this.myBirthplace.province })
            this.municipalList = res.data
        },
        async findCounty() {
            let res = await areaApi.getCountyList({ code: this.myBirthplace.municipal })
            this.countyList = res.data
        },
        makeBirthPlace() {
            this.userInfo.birthplace = ''
            const province = this.provinceList.find(province => province.code === this.myBirthplace.province)
            this.userInfo.birthplace = province.value

            const municipal = this.municipalList.find(municipal => municipal.code === this.myBirthplace.municipal)
            this.userInfo.birthplace += municipal.value

            const county = this.countyList.find(county => county.code === this.myBirthplace.county)
            this.userInfo.birthplace += county.value

        },
        pushUserInfo() {
            console.log(this.userInfo)
            this.$refs.userInfoForm.validate(async (valid) => {
                if (valid) {
                    let res = null
                    res = await userApi.register(this.userInfo)
                    if(res.success){
                        this.$message.success("报到信息填写成功！")
                    }else
                        this.$message.error("失败，请检查信息填写是否正确")
                }
            })
        },
        // 上传照片成功回调
        handleAvatarSuccess(res, file) {
            this.userInfo.photoId = res.data
            console.log(res)
            this.$forceUpdate()
        },
        // 上传校验
        beforeAvatarUpload(file) {
            const isLt2M = file.size / 1024 / 1024 < 2

            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!')
            }
            return isLt2M
        },

    },
    created() {
        this.init()
    },
}

</script>

<style lang="scss" scoped>
.left {
    width: 70%;
    float: left;
    padding: 20px;
    height: 82vh;
}

.right {
    width: 30%;
    float: right;
    padding-top: 20px;
    height: 82vh;
}

.button {
    float: right;
    padding-top: 30px;
}

//用户头像
.avatar-uploader .el-upload {
    border: 1px dashed #afaeae !important;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar-uploader img {
    width: 178px;
    height: 178px;
    display: block;
}
</style>